from django.shortcuts import render, redirect
# 导包
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
# 导入类视图
from django.views import View

# from myapp.models import User
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
# 导入加密库
import hashlib
# 导入图片库
# 绘画库
from PIL import ImageDraw
# 字体库
from PIL import ImageFont
# 图片库
from PIL import Image
# 随机库
import random
# 文件流
import io

import requests

# 导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

# 导入原生sql模块
from django.db import connection

import jwt

# 导入redis数据库
import redis

# 导入时间模块
import time

# 导入公共目录变量
from mydjango.settings import BASE_DIR

# 导包
from django.db.models import Q, F

# 导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

from .models import *


# 方法视图
def myindex(request):
    return HttpResponse('这里是首页')


# 类试图
class MyView(View):
    greeting = '你好啊'

    def get(self, request):
        user = User.objects.all()
        # 模板渲染
        return render(request, 'users.html', locals())


# 添加用户
class AddUser(View):

    def get(self, request):
        return render(request, 'add.html')

    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        type = request.POST.get('type')
        img = request.FILES.get('img')

        # 拼接路径
        img_path = os.path.join(UPLOAD_ROOT, img.name)

        with open(img_path, 'wb') as f:
            for chunk in img.chunks():
                f.write(chunk)

        User.objects.create(username=username, password=password, img=img.name, type=int(type))
        meg = '添加成功'
        return redirect('/', locals())


# 删除用户
class Delete(View):
    def get(self, request):
        id = request.GET.get('id')
        User.objects.filter(id=id).delete()
        return redirect('/')


# 修改用户
class UploadUser(View):
    def get(self, request):
        id = request.GET.get('id')
        user = User.objects.filter(id=id)[0]
        if user:
            return render(request, 'upload.html', locals())
        else:
            return HttpResponse('修改错误')

    def post(self, request):
        id = request.GET.get('id')
        username = request.POST.get('username')
        password = request.POST.get('password')
        types = request.POST.get('types')
        img = request.FILES.get('img')

        # 拼接路径
        img_path = os.path.join(UPLOAD_ROOT, img.name)

        with open(img_path, 'wb') as f:
            for chunk in img.chunks():
                f.write(chunk)

        User.objects.filter(id=id).update(username=username, password=password, img=img.name, type=int(types))
        meg = '添加成功'
        return redirect('/', locals())
